//
//  MoviePlayerViewController.m
//  iBaby365v2
//
//  Created by admin on 14/12/8.
//  Copyright (c) 2014年 suplus. All rights reserved.
//

#import "MoviePlayerViewController.h"
#import <MediaPlayer/MediaPlayer.h>

@interface MoviePlayerViewController ()
@property (nonatomic, strong) MPMoviePlayerViewController *moviePlayerView;
@end

@implementation MoviePlayerViewController



- (void)viewDidLoad
{
    [super viewDidLoad];
   
    [self addVideoViewController];
    
    [self.moviePlayerView.moviePlayer play];
    [self addNotification];
}


/**
 *  需要横屏 必须要实现MPMoviePlayerViewController而不是MPMoviePlayerController
 *  如果是直接播放或者应用支持旋转则可直接使用MPMoviePlayerController
 */
- (void)addVideoViewController
{
    self.moviePlayerView = [[MPMoviePlayerViewController alloc] initWithContentURL:self.movieURL];
//    self.moviePlayerView.moviePlayer.controlStyle = MPMovieControlStyleFullscreen;
    self.moviePlayerView.view.frame = CGRectMake(0, 0, self.view.bounds.size.height, self.view.bounds.size.width);
    self.moviePlayerView.view.center = CGPointMake(self.view.bounds.size.width/2, self.view.bounds.size.height/2);
    CGAffineTransform transform = CGAffineTransformMakeRotation(M_PI/2);
    [self.moviePlayerView.view setTransform:transform];
    [self.view addSubview:self.moviePlayerView.view];
}

#pragma mark - 添加通知
- (void)addNotification
{
    // 1. 添加播放状态的监听
    NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
    [nc addObserver:self selector:@selector(stateChanged) name:MPMoviePlayerPlaybackStateDidChangeNotification object:nil];
    // 2. 播放完成
    [nc addObserver:self selector:@selector(finished) name:MPMoviePlayerPlaybackDidFinishNotification object:nil];
    // 3. 全屏
    [nc addObserver:self selector:@selector(finished) name:MPMoviePlayerDidExitFullscreenNotification object:nil];
}

- (void)finished
{
    // 1. 删除通知监听
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    // 2. 返回上级窗体
    // 谁申请,谁释放!
    [self.delegate moviePlayerDidFinished];
    NSLog(@"完成");
}

/**
 MPMoviePlaybackStateStopped,           停止
 MPMoviePlaybackStatePlaying,           播放
 MPMoviePlaybackStatePaused,            暂停
 MPMoviePlaybackStateInterrupted,       中断
 MPMoviePlaybackStateSeekingForward,    下一个
 MPMoviePlaybackStateSeekingBackward    前一个
 */
- (void)stateChanged
{
    switch (self.moviePlayerView.moviePlayer.playbackState) {
        case MPMoviePlaybackStatePlaying:
            NSLog(@"播放");
            break;
        case MPMoviePlaybackStatePaused:
            NSLog(@"暂停");
            break;
        case MPMoviePlaybackStateStopped:
            // 执行[self.moviePlayer stop]或者前进后退不工作时会触发
            NSLog(@"停止");
            break;
        default:
            break;
    }
}


@end
